/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.start.model;

import business.service.MongoDbFactory;
import com.google.common.base.Joiner;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.star.common.CateData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;

/**
 *
 * @author ngotandieu
 */
public class CateModel {

    private static final String CATE_COLLECTION = "category";
    private static final Logger logger = Logger.getLogger(CateModel.class);
    private static final Lock createLock_ = new ReentrantLock();
    private static CateModel _instance = null;
    
    public static CateModel getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new CateModel();

                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }

    public CateModel() {
        try {
        } catch (Exception ex) {
            logger.error("CateModel: " + ex);
        }
    }

    public String addCate(CateData cateData) {
        String id = "";
        try {
            BasicDBObject basicDBObject = new BasicDBObject("name", cateData.getName())
                    .append("position", cateData.getPosition())
                    .append("profiles", "")
                    .append("created", System.currentTimeMillis());
            
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(CATE_COLLECTION);
            coll.insert(basicDBObject);
            
            ObjectId objectId = (ObjectId)basicDBObject.get( "_id" );
            id = objectId.toString();
        } catch (Exception ex) {
            logger.error("CateModel.addCate: " + ex.getMessage(), ex);
        }
        return id;
    }

    public boolean editCate(CateData cateData) {
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(CATE_COLLECTION);
            
            BasicDBObject basicDBObject = new BasicDBObject("name", cateData.getName())
                    .append("position", cateData.getPosition());
            
            BasicDBObject updateDBObject = new BasicDBObject("$set", basicDBObject);
            BasicDBObject searchDBQuery = new BasicDBObject("_id", new ObjectId(cateData.getId()));
            coll.update(searchDBQuery, updateDBObject);
            return true;
        } catch (Exception ex) {
            logger.error("CateModel.editCate: " + ex.getMessage(), ex);
        } finally {
            
        }
        return false;
    }

    public boolean deleteCate(String id) {
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(CATE_COLLECTION);
            coll.remove(new BasicDBObject("_id", new ObjectId(id)));
            
            return true;
        } catch (Exception ex) {
            logger.error("CateModel.deleteCate: " + ex.getMessage(), ex);
        }
        return false;
    }

    public List<CateData> getCate(int start, int limit) {
        List<CateData> lstCate = null;
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", -1);
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(CATE_COLLECTION);
            DBCursor cursor = coll.find().sort(basicDBObject);
            if (limit != -1) {
                cursor = cursor.skip(start).limit(limit);
            }
            lstCate = new ArrayList<>();
            while (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String id = ((ObjectId)dbObject.get("_id")).toString();
                String name = (String) dbObject.get("name");
                int position = (int) dbObject.get("position");
                long created = (long) dbObject.get("created");

                CateData cateData = new CateData(id, name, position, created);
                lstCate.add(cateData);
            }
        } catch (Exception ex) {
            logger.error("CateModel.getCate: " + ex.getMessage(), ex);
        } 
        return lstCate;
    }

    public CateData getCateById(String id) {
        CateData cateData = null;
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", new ObjectId(id));
            
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(CATE_COLLECTION);
            DBCursor cursor = coll.find(basicDBObject);
            if(cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String name = (String)dbObject.get("name");
                int positon = (Integer)dbObject.get("position");
                long created = (Long)dbObject.get("created");
                cateData = new CateData(id, name, positon, created);
            }
        } catch(Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
        return cateData;
    }

    public boolean setProfileForCate(String id, List<String> lstCats) {
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(CATE_COLLECTION);
            for (String cateId : lstCats) {
                BasicDBObject basicDBObject = new BasicDBObject("_id", cateId);
                DBCursor cursor = coll.find(basicDBObject);
                if(cursor.hasNext()) {
                    DBObject dbObject = cursor.next();
                    String profiles = (String)dbObject.get("profiles");
                    List<String> lstAccess = null;
                    if(!profiles.isEmpty()) {
                        lstAccess = Arrays.asList(profiles.split("\\s*,\\s*"));
                    } else {
                        lstAccess = new ArrayList<>();
                    } 
                    if(!lstAccess.contains(id)) {
                        lstAccess.add(id);
                    }
                    profiles = Joiner.on(",").join(lstAccess);
                    
                    basicDBObject = new BasicDBObject("profiles", profiles);
                    BasicDBObject updateDBObject = new BasicDBObject("$set", basicDBObject);
                    BasicDBObject searchDBQuery = new BasicDBObject("_id", new ObjectId(cateId));
                    coll.update(searchDBQuery, updateDBObject);
                }
                
            }
            
        } catch(Exception ex) {
            logger.error(ex.getMessage(), ex);
            return false;
        }
        return true;
    }
}
